using MediatR;
using Microsoft.AspNetCore.Mvc;
using SupplierCustomerManagement.Read.API.Applications.Commands.bankaccounts;
using B.S.RbacData.ErrorCode;

namespace SupplierCustomerManagement.Read.API.Controllers
{
    /// <summary>
    /// 银行账户查询控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class BankAccountsController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<BankAccountsController> _logger;

        public BankAccountsController(IMediator mediator, ILogger<BankAccountsController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        /// <summary>
        /// 获取银行账户列表
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>银行账户列表</returns>
        [HttpGet]
        public async Task<ActionResult<ApiPaging<BankAccountListDto>>> GetBankAccounts([FromQuery] GetBankAccountsQuery query)
        {
            try
            {
                var result = await _mediator.Send(query);

                _logger.LogInformation("成功处理获取银行账户列表请求，返回 {Count} 条记录", 
                    result.PageData?.Count ?? 0);

                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理获取银行账户列表请求时发生异常");
                
                var errorResult = new ApiPaging<BankAccountListDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"获取银行账户列表失败: {ex.Message}",
                    data = default,
                    TotalCount = 0,
                    PageCount = 0,
                    PageData = new List<BankAccountListDto>()
                };

                return StatusCode(500, errorResult);
            }
        }

        /// <summary>
        /// 获取账户关系枚举信息
        /// </summary>
        /// <returns>账户关系枚举信息</returns>
        [HttpGet]
        public async Task<ActionResult<ApiResult<AccountRelationshipEnumsDto>>> GetAccountRelationshipEnums()
        {
            try
            {
                var query = new GetAccountRelationshipEnumsQuery();
                var result = await _mediator.Send(query);

                _logger.LogInformation("成功处理获取账户关系枚举信息请求");

                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理获取账户关系枚举信息请求时发生异常");
                
                var errorResult = new ApiResult<AccountRelationshipEnumsDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"获取账户关系枚举信息失败: {ex.Message}",
                    data = default
                };

                return StatusCode(500, errorResult);
            }
        }
    }
}